import json
from flask import render_template, request, redirect, flash, url_for, send_from_directory, session, current_app, jsonify
from flask_ckeditor import upload_fail, upload_success

from app.admin import admin
from app.admin.forms import PostForm, LoginForm, CategoryForm, AdminForm
from app.models import Admin, Post, Category
from flask_login import login_required, login_user, current_user, logout_user
from core.db import db
from core.exception import ParameterException
from core.utils import serialize
from werkzeug.utils import secure_filename
import os
import uuid


def random_filename(filename):
    ext = os.path.splitext(filename)[1]
    new_filename = uuid.uuid4().hex + ext
    return new_filename


@admin.route('/img', methods=['GET', 'POST'])
def admin_img_up(name="public"):
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            return jsonify('')
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            return jsonify('')
        if file:
            try:
                # filename = secure_filename(file.filename)
                filename = random_filename(secure_filename(file.filename))
                file.save(os.path.join(current_app.config['UPLOAD_PATH'], filename))
                return jsonify('/static/uploads/' + filename)
            except Exception as e:
                return jsonify(str(e))
        else:
            return jsonify('')
    return jsonify('')


@admin.route('/login', methods=['GET', 'POST'])
def admin_login():
    form = LoginForm()
    if form.validate_on_submit():
        admin = Admin.query.filter_by(username=form.username.data).first()
        if admin and admin.check_admin_password(form.password.data):
            login_user(admin, remember=True)
            next = request.args.get('next')
            if not next or not next.startswith('/'):
                next = url_for('admin.admin_index')
            return redirect(next)
        else:
            flash('账号不存在或者密码有误', 'error')
            return redirect(url_for('admin.admin_login'))
    else:
        if current_user.is_authenticated and request.blueprint in current_user.get_id():
            return redirect(url_for('admin.admin_index'))
        return render_template('admin/admin-login.html', form=form), 200


@admin.route('/logout', methods=['GET', 'POST'])
@login_required
def admin_logout():
    # if not current_user.is_authenticated:
    #     return redirect(url_for('admin.admin_login'))
    logout_user()
    return redirect(url_for('admin.admin_login'))


@admin.route('/', methods=['GET'])
@login_required
def admin_index():
    return render_template('admin/admin-index.html')


@admin.route('/user', methods=['GET', 'POST'])
@login_required
def admin_user():
    form = PostForm()
    form.top.default = 1
    if form.validate_on_submit():
        # 文件上传
        flash(json.dumps(form.data), 'success')
        return redirect(url_for('admin.admin_post'))  # route
    return render_template('admin/admin-post-edit.html', form=form), 200


@admin.route('/user/list', methods=['GET'])
@login_required
def admin_user_list():
    return render_template('admin/admin-post.html'), 200


@admin.route('/category', methods=['GET', 'POST'])
@login_required
def admin_category():
    form = CategoryForm()
    if form.validate_on_submit():
        # 文件上传
        category = Category(
            name=form.name.data,
            status=form.status.data
        )
        db.session.add(category)
        db.session.commit()

        if True:
            return redirect(url_for('admin.admin_category_list'))  # route
        else:
            flash('创建失败', 'success')
            return redirect(url_for('admin.admin_category'))
    return render_template('admin/admin-category-edit.html', form=form), 200


@admin.route('/category/list', methods=['GET'])
@login_required
def admin_category_list():
    categories = Category.query.all()
    return render_template('admin/admin-category.html', list=categories), 200


@admin.route('/category/delete/<int:id>', methods=['GET'])
@login_required
def admin_category_delete(id=0):
    # if post_id <= 0:
    #     return ParameterException()
    category = Category.query.filter_by(id=id).first_or_404()
    db.session.delete(category)
    db.session.commit()
    return redirect(url_for('admin.admin_category_list'))  # route


@admin.route('/post', methods=['GET', 'POST'])
@login_required
def admin_post():
    form = PostForm()
    # form.category.choices = [(v.id, v.name) for v in Category.query.all()]
    # form.top.data = 0
    if form.validate_on_submit():
        # 文件上传
        # content_html = request.form['my-editormd-html-code']
        post = Post(
            title=form.title.data,
            desc=form.desc.data,
            cover=form.cover.data,
            category_id=form.category.data,
            top=form.top.data,
            body=form.body.data,
            # content_html=markdown(form.content.data),
            # content_html=content_html
        )

        db.session.add(post)
        db.session.commit()

        if True:
            return redirect(url_for('admin.admin_post_list'))  # route
        else:
            flash('创建失败', 'success')
            return redirect(url_for('admin.admin_post'))
    return render_template('admin/admin-post-edit.html', form=form), 200


@admin.route('/post/list', methods=['GET'])
@login_required
def admin_post_list():
    posts = Post.query.all()
    return render_template('admin/admin-post.html', list=posts), 200


@admin.route('/post/delete/<int:id>/', methods=['GET'])
@login_required
def admin_post_delete(id):
    # if post_id <= 0:
    #     return ParameterException()
    post = Post.query.filter_by(id=id).first_or_404()
    db.session.delete(post)
    db.session.commit()
    return redirect(url_for('admin.admin_post_list'))  # route


@admin.route('/files/<filename>')
def uploaded_files(filename):
    path = current_app.config['UPLOAD_PATH']
    return send_from_directory(path, filename)


@admin.route('/upload', methods=['POST'])
def upload():
    f = request.files.get('upload')
    extension = f.filename.split('.')[-1].lower()
    if extension not in ['jpg', 'gif', 'png', 'jpeg']:
        return upload_fail(message='Image only!')
    f.save(os.path.join(current_app.config['UPLOAD_PATH'], f.filename))
    url = url_for('uploaded_files', filename=f.filename)
    return upload_success(url=url)


@admin.route('/comment', methods=['GET', 'POST'])
@login_required
def admin_comment():
    form = PostForm()
    form.top.default = 1
    if form.validate_on_submit():
        # 文件上传
        flash(json.dumps(form.data), 'success')
        return redirect(url_for('admin.admin_post'))  # route
    return render_template('admin/admin-post-edit.html', form=form), 200


@admin.route('/comment/list', methods=['GET'])
@login_required
def admin_comment_list():
    return render_template('admin/admin-post.html'), 200


@admin.route('/admin', methods=['GET', 'POST'])
@login_required
def admin_admin():
    form = AdminForm()
    if form.validate_on_submit():
        # 文件上传
        flash(json.dumps(form.data), 'success')
        return redirect(url_for('admin.admin_admin'))  # route
    return render_template('admin/admin-admin-edit.html', form=form), 200


@admin.route('/admin/list', methods=['GET'])
@login_required
def admin_admin_list():
    return render_template('admin/admin-admin.html'), 200


@admin.route('/role', methods=['GET', 'POST'])
@login_required
def admin_role():
    form = PostForm()
    form.top.default = 1
    if form.validate_on_submit():
        # 文件上传
        flash(json.dumps(form.data), 'success')
        return redirect(url_for('admin.admin_post'))  # route
    return render_template('admin/admin-post-edit.html', form=form), 200


@admin.route('/role/list', methods=['GET'])
@login_required
def admin_role_list():
    return render_template('admin/admin-post.html'), 200


@admin.route('/auth', methods=['GET', 'POST'])
@login_required
def admin_auth():
    form = PostForm()
    form.top.default = 1
    if form.validate_on_submit():
        # 文件上传
        flash(json.dumps(form.data), 'success')
        return redirect(url_for('admin.admin_post'))  # route
    return render_template('admin/admin-post-edit.html', form=form), 200


@admin.route('/auth/list', methods=['GET'])
@login_required
def admin_auth_list():
    return render_template('admin/admin-post.html'), 200
